import wx
import os.path

from plugins.base.pane import Pane

class DebuggerPane(Pane):
  def __init__(self, parent):
    Pane.__init__(self, parent)

    sizer = wx.BoxSizer(wx.VERTICAL)
    self.SetSizer(sizer)

    self._output = wx.TextCtrl(self, style=wx.TE_MULTILINE|wx.TE_PROCESS_ENTER|wx.TE_READONLY)
    sizer.Add(self._output, True, wx.EXPAND)

    hsizer = wx.BoxSizer(wx.HORIZONTAL)
    sizer.Add(hsizer, False, wx.EXPAND)

    self._input = wx.TextCtrl(self)
    hsizer.Add(self._input, True, wx.EXPAND)

    self._submit = wx.Button(self, -1, 'Submit')
    hsizer.Add(self._submit, False, wx.EXPAND)

    wx.CallAfter(self.Layout)

    self._process = None

    self.Bind(wx.EVT_IDLE, self.onIdle)
    self.Bind(wx.EVT_END_PROCESS, self.onProcessEnded)
    self.Bind(wx.EVT_BUTTON, self.onSubmit, self._submit)

  def __del__(self):
    if self._process is not None:
      self._process.Detach()
      self._process.CloseOutput()
      self._process = None

  def getConfigFileName(self):
    return os.path.dirname(__file__) + os.path.sep + 'config.cfg'

  def runScript(self, filename):
    assert os.path.exists(filename)
    assert self._process is None

    self._output.Clear()
    self._output.AppendText('-- Run script file: %s --------------%s' % (filename, os.linesep))

    cmd = 'python %s --debug=true --workpath="../"' % filename
    self._process = wx.Process(self)
    self._process.Redirect()
    pid = wx.Execute(cmd, wx.EXEC_ASYNC, self._process)

  def stopScript(self):
    if self._process is not None:
      self._process.CloseOutput()
      self._process = None

      self._output.AppendText('-- Script file done --------------%s' % os.linesep)

  def onIdle(self, evt):
    if self._process is not None:
      stream = self._process.GetInputStream()
      if stream is not None:
        while stream.CanRead():
          text = stream.read()
          self._output.AppendText(text)

  def onProcessEnded(self, evt):
    if self._process is not None:
      stream = self._process.GetInputStream()
      if stream is not None:
        while stream.CanRead():
          text = stream.read()
          self._output.AppendText(text)

    self._process = None
    self._output.AppendText('-- Script file done --------------%s' % os.linesep)

  def onSubmit(self, evt):
    text = self._input.GetValue()
    self._input.SetValue('')
    self._process.GetOutputStream().write(text + '\n')
    self._input.SetFocus()